package com.cybertron.ironhide.search.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.cybertron.ironhide.search.common.Constants;

public class SuggestUtil {

	public static final String SUGGEST_URL = "http://completion.amazon.com/search/complete"
			+ "?method=completion&q={0}&search-alias=aps&client=amazon-search-ui&mkt=1&fb=1&xcat=0&sc=1&noCacheIE=1382790721795";

	@SuppressWarnings("unchecked")
	public static List<String> suggest(String keyWord) {
		if (StringUtils.isBlank(keyWord)) {
			return null;
		}
		if (Constants.IS_DEBUG) {
			return null;
		}
		try {
			keyWord = URLEncoder.encode(keyWord, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(
				MessageFormat.format(SUGGEST_URL, keyWord));
		String s = null;
		try {
			HttpResponse response = client.execute(httpGet);
			HttpEntity e = response.getEntity();
			s = EntityUtils.toString(e);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<String> results = null;
		if (s != null) {
			results = new ArrayList<String>();
		} else {
			return null;
		}
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			List<Object> arr = objectMapper.readValue(s,
					new TypeReference<List<Object>>() {
					});
			if (arr != null && arr.size() != 0) {
				results = (List<String>) arr.get(1);
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return results;
	}
}
